package com.lzt.admin.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lzt.admin.api.cache.CacheConstantsAPI;
import com.lzt.admin.common.utils.ConverUtil;
import com.lzt.admin.common.redis.config.RedisCore;
import com.lzt.admin.common.sys.config.SysConfigProperites;
import com.lzt.admin.dto.config.SysConfigDTO;
import com.lzt.admin.system.dao.SysConfigDAO;
import com.lzt.admin.system.service.SysConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@RequiredArgsConstructor
@EnableConfigurationProperties(SysConfigProperites.class)
public class SysConfigServiceImpl implements SysConfigService, CacheConstantsAPI {
    private final SysConfigProperites sysConfigProperites;
    private final SysConfigDAO configDAO;
    private final RedisCore redisCore;
    @Override
    public boolean selectCaptchaEnabled() throws JsonProcessingException {
        String captchaEnabled = selectConfigByKey(sysConfigProperites.getCaptchaEnabled()).replace("\"","");
        return ConverUtil.toBool(Optional.ofNullable(captchaEnabled).orElse("false"));

    }
    @Override
    public String selectConfigByKey(String configKey) throws JsonProcessingException {
        String configValue = Convert.toStr(redisCore.getCacheObject(getCacheKey(configKey)));
        if(StrUtil.isBlank(configValue)){
            SysConfigDTO retConfig = configDAO.selectConfig(configKey);
            Optional.ofNullable(retConfig).orElseThrow(()->new RuntimeException("没有找到匹配的键值"));
            redisCore.setCacheObject(getCacheKey(configKey),retConfig.getConfigValue());
            return Optional.ofNullable(retConfig.getConfigValue()).orElse("");
        }
        return configValue;
    }
    private String getCacheKey(String configKey)
    {
        return SYS_CONFIG_KEY + configKey;
    }
}
